<template lang="pug">
  .clearfix
    Modal(
      width="520"
      v-model="isShowImportStandingBookModal"
      title="商保台账导入"
      class-name="vertical-center-modal"
    )
      .search-form
        Form.ivu-row.has-rules-item2(ref="formData" :model="formData" :rules="rules" :label-width="100")
          FormItem.form-item.ivu-col.pr-20(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
            template(v-if="item.type === 'select'")
              Row
                Col(span="15")
                  Select(v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable)
                    Option(
                      v-for="(c_item, index) in arrListDown[item.options]"
                      :value="c_item.securityNO"
                      :key="index"
                    ) {{ c_item.securityNO }}
                Col.pl-20(span="9")
                  Button(v-if="item.model === 'commercialNo'" @click="exportSecurityNos") 导出商保编号
            template(v-if="item.type === 'datePicker'")
              Row
                Col(span="15")
                  DatePicker.w-100(v-model="formData[item.model]" placeholder="请选择" type="month" format="yyyy-MM" @on-change="handleChangeDatePicker(item.model, $event)")
            template(v-if="item.type === 'radio'")
              RadioGroup(v-model="formData[item.model]")
                Radio.display-inline-block(v-for="c_item of arrListDown[item.radioArr]" :label="c_item.value") {{c_item.label}}
            template(v-if="item.type === 'file'")
              Button.pull-left.mr-10(:to="templateDownLoadUrl" target="_blank") 模板下载
              //- Upload(@before="handleBeforeUpload" @upload="uploadSuccess" :isCanUpload="true")
              Upload.pull-left.mb-5(:before-upload="handleBeforeUpload" ref="upload" :data="formData" :show-upload-list="false" accept=".xls, .xlsx" :action="baseUrl + 'api/FinanceCPayable/ImportCPayableBill'" :on-success="uploadSuccess" :headers="headers")
                Button.download-btn(type="info" :disabled="!formData.type") 导入
              Tag(v-if="file") {{file.name}}

      .clearfix(slot="footer")
        Button(type="text" @click="cancel") 取消
        Button(type="primary" @click="handleSubmit" :loading="!isCanSubmit") 确定
</template>

<script>
import { FinanceSSPayableApi } from '@/api/FinanceSSPayable.api.js'
import { EmployeesApi } from '@/api/Employees.api.js'
import { Common } from '@/utils/common.js'
import Cookies from 'js-cookie'
// import Upload from '@/components/upload/upload'
// import UploadZip from '@/components/upload/uploadZip'
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro.replace('/api', '/')
export default {
  name: '',

  props: {
  },

  components: {
    // Upload,
    // UploadZip
  },

  data () {
    return {
      headers: {
        'Authorization': 'Bearer ' + Cookies.get('clientToken')
      },
      baseUrl: baseUrl,
      employeeId: '',
      isShowImportStandingBookModal: false,
      tempModel: '',
      formData: {
        commercialNo: '',
        feeYearMonth: '',
        periodYear: '',
        periodMonth: '',
        type: null // 1-新增，2-续保
      },
      formItem: [
        { type: 'datePicker', label: '费用月份', placeholder: '请选择费用月份', prop: 'feeYearMonth', model: 'feeYearMonth', style: 'ivu-col-span-24' },
        { type: 'select', label: '商保编号', placeholder: '请选择商保编号', prop: 'commercialNo', model: 'commercialNo', style: 'ivu-col-span-24', options: 'securityNos' },
        { type: 'radio', label: '导入类型', placeholder: '请选择导入类型', prop: 'type', model: 'type', style: 'ivu-col-span-24', radioArr: 'typeArr' },
        { type: 'file', label: '选择文件', placeholder: '请选择文件', prop: 'file', model: 'file', style: 'ivu-col-span-24', files: [] }
      ],
      rules: {
        commercialNo: [
          { required: true, message: '请选择商保编号', trigger: 'change' }
        ],
      },
      arrListDown: {
        securityNos: [],
        typeArr: [{ value: '1', label: '新增' }, { value: '2', label: '续保' }],
      },
      params: { // 文件上传参数
        ID: '',
        rowVersion: '',
        categoryname: '',
        Atta: ''
      },
      accessoryArr: [],
      file: null,
      templateDownLoadUrl: baseUrl + 'Content/Template/商保台账导入通用模板.xls?random=' + Math.floor(Math.random() * 10),
      isCanSubmit: true
    }
  },

  watch: {
  },

  mounted () {
    // this.getSecurityNos()
  },

  methods: {
    // 获取保险编号
    async getSecurityNos () {
      var params = {
        type: 3,
        feedate: this.formData.feeYearMonth || this.$moment(new Date()).format('YYYY-MM'),
        isall: 0
      }
      let res = await FinanceSSPayableApi.getSecurityNos(params)
      console.log('获取保险编号res: ', res)
      if (res.status === 200 && res.data.success) {
        this.arrListDown.securityNos = res.data.data
      } else {
        this.arrListDown.securityNos = []
      }
    },

    // 导出编号
    async exportSecurityNos () {
      var params = {
        type: 3,
        feedate: this.formData.feeYearMonth || this.$moment(new Date()).format('YYYY-MM')
      }
      console.log('params: ', params)
      let res = await FinanceSSPayableApi.exportSecurityNos(params)
      console.log('导出编号res: ', res)
      if (res.status === 200 && res.data.success) {
        console.log('❤ 返回链接: ', baseUrl + res.data.message)
        window.open(baseUrl + res.data.message, '_blank')
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },
  
    // 上传成功
    uploadSuccess (res, row) {
      console.log('上传成功res: ', res)
      console.log('上传成功row: ', row)
      if (res.code === 200 && res.success) {
        this.$Message.success(res.message)
        this.$emit('uploadSuccess')
        this.isShowImportStandingBookModal = false
      } else {
        this.isCanSubmit = true
        this.$Message.error({
          content: res.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 确定导入
    handleSubmit () {
      this.isCanSubmit = false
      console.log('this.formData: ', this.formData)
      this.$refs.formData.validate((valid) => {
        if (valid) {
          console.log('ok')
          if (this.file) {
            this.$refs.upload[0].post(this.file)
            this.upload = false
            this.file = null
          } else {
            this.isCanSubmit = true
            this.$Message.warning('请选择文件！')
          }
        } else {
          this.isCanSubmit = true
        }
      })
    },

    // showModal () {
    //   this.isShowImportStandingBookModal = true
    //   Object.keys(this.formData).forEach(key => {
    //     this.formData[key] = ''
    //   })
    // },

    // 取消导入
    cancel () {
      this.file = null
      this.isShowImportStandingBookModal = false
    },
    show () {
      this.$refs.formData.resetFields({})
      this.isCanSubmit = true
      this.file = null
      this.isShowImportStandingBookModal = true
    },

    // 上传前文件
    handleBeforeUpload (file) {
      // this.file = file
      // console.log(file)
      // return false
      var str = file.name.substring(file.name.lastIndexOf('.'), file.name.length)
      if (['.xls', '.xlsx'].indexOf(str) == -1) {
        this.$Message.warning('仅支持上传xlsx文件')
        this.file = null
      } else {
        // this.errorData.isError = false
        this.file = file
        console.log('file: ', this.file)
      }
      return false
    },

    // 时间选择控件
    handleChangeDatePicker (model, value) {
      this.formData[model] = value
      var timeArr = value.split('-')
      this.formData.periodYear = timeArr[0]
      this.formData.periodMonth = timeArr[1]
      this.getSecurityNos()
    },

    // 单选
    radioChange (value) {
      console.log('value: ', value)
    }
  }
}
</script>

<style lang="less" scope>
</style>
